package com.travelranking.rest;

import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;

import com.travelranking.pojo.Travel;

public class RestClient {
	
	private String uri = "http://localhost:8080/travel-ranking/services/rest/travel/";
	
	public Object add(Travel t){
		HttpClient cliente = new DefaultHttpClient();
		HttpPut put = new HttpPut(uri
				+t.getCity()
				+"/"+t.getOpinion()
				+"/"+t.getRank());
		try {
			HttpResponse response = cliente.execute(put);
			System.out.println(response.toString());
		} catch (Exception e){
			throw new RuntimeException ("Falhou o put",e);
		}
		return null;
	}
	
	public Object addObjeto(Travel t){
		
		HttpClient cliente = new DefaultHttpClient();
		HttpPost post = new HttpPost(uri);
		
		HttpParams def = null;
//		def = new BasicHttpParams ();
		def = post.getParams();
		def.setParameter("city", t.getCity());
		def.setParameter("opinion", t.getOpinion());
		def.setIntParameter("rank", t.getRank());
		post.setParams(def);
		
		try {
			HttpResponse response = cliente.execute(post);
			System.out.println(response.toString());
		} catch (Exception e){
			throw new RuntimeException ("Falhou o post",e);
		}
		return null;
	}
	

	public Object get(String path, String filter){
		if (path == null){
			path = "list";
		}
		
		HttpClient cliente = new DefaultHttpClient();
		HttpGet get = new HttpGet(uri+path);
		byte[] resposta = new byte[2048];
		
		try {
			HttpResponse response = cliente.execute(get);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				System.out.println(entity.getContentType().getValue());
			    InputStream instream = entity.getContent();
			    instream.read();
			    int l = -1;
			    
			   //s while (re)
			    
			    while ((l = instream.read(resposta)) != -1) {
			    	System.out.println(l);
			    }
			}
		} catch (Exception e) {
			e.printStackTrace();
		}		
		
		return resposta;
	}

	public String getUri() {
		return uri;
	}

	public void setUri(String uri) {
		this.uri = uri;
	}
	
}
